package pay;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import pay.util.payService;
import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/notify")
public class userNotifyServlet {
    public String payNotify(HttpServletRequest request) throws Exception {
        String status = payService.payNotify(request);
        if ("success".equals(status)) {
            // 用户确实支付成功，更新支付状态
            try (Connection connection = DBUtil.getConnection()) {
                String sql = "UPDATE alluserpayhistory SET status = ? WHERE order_id = ?";
                try (PreparedStatement stmt = connection.prepareStatement(sql)) {
                    stmt.setString(1, "paid");
                    stmt.setString(2, request.getParameter("out_trade_no")); // 支付宝回调通知中包含了订单号
                    int rowsAffected = stmt.executeUpdate(); // 执行更新操作
                    if (rowsAffected > 0) {
                        System.out.println("支付状态更新成功");
                    } else {
                        System.out.println("未找到对应的订单，支付状态更新失败");
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("数据库操作失败: " + e.getMessage());
            }
        }
        return status;
    }
}